/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：CapitalRecordsService.java
 * History:
 *         2019年6月17日: Initially created, CJH.
 */
package club.coderleague.ilsp.service.capitalrecords;

import java.math.BigDecimal;
import java.util.Date;

import javax.validation.ValidationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import club.coderleague.ilsp.common.domain.enums.CapitalChangedReason;
import club.coderleague.ilsp.common.domain.enums.CapitalRecordType;
import club.coderleague.ilsp.common.domain.enums.EntityState;
import club.coderleague.ilsp.common.domain.enums.NotifyType;
import club.coderleague.ilsp.common.exception.MessageInfoException;
import club.coderleague.ilsp.dao.CapitalRecordsDao;
import club.coderleague.ilsp.dao.MerchantsDao;
import club.coderleague.ilsp.dao.OrdersDao;
import club.coderleague.ilsp.entities.Capitalrecords;
import club.coderleague.ilsp.entities.Merchants;
import club.coderleague.ilsp.entities.Orders;
import club.coderleague.ilsp.service.interfaces.AliyunInterfaceService;

/**
 * 资金记录Service
 * 
 * @author CJH
 */
@Service
public class CapitalRecordsService {
	/**
	 * 资金记录Dao
	 */
	private @Autowired CapitalRecordsDao capitalRecordsDao;
	
	/**
	 * 订单Dao
	 */
	private @Autowired OrdersDao ordersDao;
	
	/**
	 * 阿里云接口
	 */
	private @Autowired AliyunInterfaceService aliyunInterfaceService;
	
	/**
	 * 商户Dao
	 */
	private @Autowired MerchantsDao merchantsDao;
	
	/**
	 * 订单收入资金
	 * 
	 * @author CJH 2019年6月17日
	 * @param orderid 订单标识
	 */
	public void updateOrderRevenueCapitalByMerchantid(Long orderid) {
		// 校验参数有效性
		if (orderid == null) {
			throw new ValidationException("订单标识不能为空");
		}
		
		Orders orders = ordersDao.getOne(orderid);
		BigDecimal capital = new BigDecimal(orders.getGoodtotal());
		//TODO 订单收入资金，提成费率
		BigDecimal royaltyrate = new BigDecimal(0);
		BigDecimal royaltyamount = capital.multiply(royaltyrate);
		BigDecimal changedamount = capital.subtract(royaltyamount);
		StringBuilder reasondesc = new StringBuilder("订单收入(订单号：").append(orders.getEntityid()).append(")");
		Capitalrecords capitalrecord = new Capitalrecords(EntityState.VALID.getValue(), orders.getMerchantid(), CapitalRecordType.INCOME.getValue(), 
				CapitalChangedReason.ORDER_REVENUE.getValue(), orderid, reasondesc.toString(), capital.doubleValue(), changedamount.doubleValue(), 
				royaltyrate.doubleValue(), royaltyamount.doubleValue(), new Date());
		capitalRecordsDao.save(capitalrecord);
		Merchants merchant = merchantsDao.getOne(orders.getMerchantid());
		BigDecimal totalamount = new BigDecimal(merchant.getTotalamount().toString());
		merchant.setTotalamount(totalamount.add(changedamount).doubleValue());
		
		// 给商户发送收入通知
		aliyunInterfaceService.sendAccountRemind(NotifyType.ARRACC_REMIND, orders.getMerchantid(), changedamount.doubleValue());
	}
	
	/**
	 * 锁定资金
	 * 
	 * @author CJH 2019年7月2日
	 * @param merchantid 商户标识
	 * @param lockcapitalnum 锁定资金
	 */
	public void updateLockCapitalByMerchantid(Long merchantid, Double lockcapitalnum) {
		// 校验参数有效性
		if (merchantid == null) {
			throw new ValidationException("商户标识不能为空");
		}
		if ((lockcapitalnum = lockcapitalnum != null ? lockcapitalnum : 0d) <= 0) {
			throw new ValidationException("锁定资金不能小于等于0");
		}
		
		Merchants merchant = merchantsDao.getOne(merchantid);
		BigDecimal totalamount = new BigDecimal(merchant.getTotalamount().toString());
		BigDecimal lockedamount = new BigDecimal(merchant.getLockedamount().toString());
		BigDecimal lockcapital = new BigDecimal(lockcapitalnum.toString());
		if (totalamount.subtract(lockedamount).compareTo(lockcapital) == -1) {
			throw new MessageInfoException("账户余额不足");
		}
		merchant.setLockedamount(lockedamount.add(lockcapital).doubleValue());
	}
	
	/**
	 * 解锁资金
	 * 
	 * @author CJH 2019年7月2日
	 * @param merchantid 商户标识
	 * @param unlockcapitalnum 解锁资金
	 */
	public void updateUnlockCapitalByMerchantid(Long merchantid, Double unlockcapitalnum) {
		// 校验参数有效性
		if (merchantid == null) {
			throw new ValidationException("商户标识不能为空");
		}
		if ((unlockcapitalnum = unlockcapitalnum != null ? unlockcapitalnum : 0d) <= 0) {
			throw new ValidationException("解锁资金不能小于等于0");
		}

		Merchants merchant = merchantsDao.getOne(merchantid);
		BigDecimal lockedamount = new BigDecimal(merchant.getLockedamount().toString());
		BigDecimal unlockcapital = new BigDecimal(unlockcapitalnum.toString());
		if (lockedamount.compareTo(unlockcapital) == -1) {
			throw new MessageInfoException("锁定余额不足");
		}
		merchant.setLockedamount(lockedamount.subtract(unlockcapital).doubleValue());
	}
	
	/**
	 * 使用资金
	 * 
	 * @author CJH 2019年7月2日
	 * @param merchantid 商户标识
	 * @param usecapitalnum 使用资金
	 * @param capitalchangedreason 资金使用类型
	 * @param usereason 使用原因
	 */
	public void updateUseCapitalByMerchantid(Long merchantid, Double usecapitalnum, CapitalChangedReason capitalchangedreason, String usereason) {
		// 校验参数有效性
		if (merchantid == null) {
			throw new ValidationException("商户标识不能为空");
		}
		if (capitalchangedreason == null || capitalchangedreason.getType() != CapitalRecordType.PAY) {
			throw new ValidationException("资金使用类型无效");
		}
		if ((usecapitalnum = usecapitalnum != null ? usecapitalnum : 0d) <= 0) {
			throw new ValidationException("使用资金不能小于等于0");
		}
		
		Merchants merchant = merchantsDao.getOne(merchantid);
		BigDecimal lockedamount = new BigDecimal(merchant.getLockedamount().toString());
		BigDecimal usecapital = new BigDecimal(usecapitalnum.toString());
		if (lockedamount.compareTo(usecapital) == -1) {
			throw new MessageInfoException("锁定余额不足");
		}
		BigDecimal totalamount = new BigDecimal(merchant.getTotalamount());
		merchant.setTotalamount(totalamount.subtract(usecapital).doubleValue());
		merchant.setLockedamount(lockedamount.subtract(usecapital).doubleValue());
		Capitalrecords capitalrecord = new Capitalrecords(EntityState.VALID.getValue(), merchantid, CapitalRecordType.PAY.getValue(), 
				capitalchangedreason.getValue(), null, usereason, usecapitalnum, usecapitalnum, null, null, new Date());
		capitalRecordsDao.save(capitalrecord);
	}
}
